package com.hz.house.service;

import com.alibaba.fastjson.JSON;
import com.hz.house.bean.entity.HotQaBean;
import com.hz.house.bean.entity.HotQaCommentBean;
import com.hz.house.bean.entity.HotQaCommentReplyBean;
import com.hz.house.bean.entity.OfficialAccountbean;
import com.hz.house.bean.vo.*;
import com.hz.house.common.Constants;
import com.hz.house.common.HtmlToText;
import com.hz.house.common.ResultUtil;
import com.hz.house.common.ServiceException;
import com.hz.house.dao.HotQaMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 	今日热问业务层
 * @author lfw
 */
@Slf4j
@Service
public class HotQaService {
	

	@Autowired
	private HotQaMapper bbsMapper;
	
	@Autowired
	private BbsCacheService bbsCacheService;
	
	/**异步统计热问的访问量浏览量，线程安全*/
	private Map<Integer,Integer> hotQaVisits = new ConcurrentHashMap<>();
	 
	@Autowired
	private CommonService commonService;
	
	@Resource
	private RestTemplate restTemplate;
	
	private static String hotQaBackGroundUrl = "https://housessmall-dev-index-img-1258778894."
			+ "cos.ap-chengdu.myqcloud.com/community/rewen_day.png";
	public static String hotQabrLineUrl = "https://housessmall-dev-index-img-12587"
			+ "78894.cos.ap-chengdu.myqcloud.com/community/line.png";
	
	/**
	 *	 获取前三条今日热问，缓存5分钟
	 * @return
	 */
	public Object get3Hotqa() {
		 
		List<HotQaBean> hotqa = this.bbsCacheService.getBbsHomeHotQa();
		if(hotqa==null) {
			//初始化缓存
			hotqa = this.bbsMapper.getBbsHomeHotQaThree();
			this.bbsCacheService.setBbsHomeHotQa(hotqa);
		}
		return ResultUtil.ok(hotqa);
	}
	
	/**
	 * <p>获取热问的详情，并添加浏览量
	 * @param hotQaId
	 * @return
	 */
	public Object getHotQaDetail(Integer hotQaId,Integer customerId) {
		if(hotQaId==null)
			return ResultUtil.fail("参数错误");
		//从缓存拉取
		HotQaBean qa =getHotQa(hotQaId);
		if(qa==null)
			return ResultUtil.fail("该热问已经被删除");
		//加入浏览量
		addHotQaVisit(hotQaId);
		//加入我是否关注了这个热问
		Integer isFoucs = this.bbsMapper.isFoucsHotQa(customerId, hotQaId);
		qa.setIsHasFoucs(isFoucs!=null);
		return ResultUtil.ok(qa);
	}
	
	/**加随机访问量*/
	private void addHotQaVisit(int hotQaId) {
		Integer v = this.hotQaVisits.get(hotQaId);
		if(v==null) 
			this.hotQaVisits.put(hotQaId, getRadomInt(5,15));
		else
			this.hotQaVisits.put(hotQaId, v+getRadomInt(5, 15));
	}
	
	private int getRadomInt(int min,int max) {
		int x = new Random().nextInt(max-min)+min;
		return x;
	}
	
	public void synHotQaVisit() {
		
		//批量更新热问浏览量到数据库
		List<SimpleBean> sbs = new ArrayList<>();
		synchronized (this.hotQaVisits) {
			int size = this.hotQaVisits.size();
			log.info("本次同步今日热问浏览量数量为:" + size);
			if (this.hotQaVisits.size() == 0)
				return;
			this.hotQaVisits.forEach((k, v) -> {
				SimpleBean s = new SimpleBean();
				s.setId(k);
				s.setNum(v);
				sbs.add(s);
			});
			this.hotQaVisits.clear();
		}
		//批量更新，然后删除map缓存
		try {
			this.bbsMapper.bactchUpdateHotQaVisit(sbs);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("批量更新今日热问访问量异常",e);
		}
	}
	
	public Object getHotQaList(Integer page,Boolean myFocus,int customerId) {
		long st = System.currentTimeMillis();
		if(page==null || page<1)
			page=1;
		if(myFocus==null)
			myFocus=false;
		if(myFocus)//查询我的关注的热问
			return getMyFoucsHotQa(page,customerId);
		List<HotQaBean> ls = this.bbsCacheService.getHotQaListCache(page);
		if(ls==null) {
			int size = 10;
			//存入本页数据
			ls = this.bbsMapper.getHotQaList((page-1)*size,size);
			this.bbsCacheService.setHotQaPageCache(page,ls);
		}
		Integer total = this.bbsCacheService.getHotQaTotals();
		if(total==null) {
			total =this.bbsMapper.getHotQaTotal();
			this.bbsCacheService.setHotQaTotals(total);
		}
		Map<String,Object> m = new HashMap<>();
		m.put("rows", ls);
		m.put("total", total);
		long ed = System.currentTimeMillis();
		log.info("拉取今日热问列表第"+page+"页耗时："+(ed-st)+"ms!");
		return ResultUtil.ok(m);
	}
	
	//查询我关注的热问
	private Object getMyFoucsHotQa(Integer page,int customerId) {
		Map<String,Object> m = new HashMap<>();
	
		int total = this.bbsMapper.getMyFoucsHotQaTotal(customerId);
		if(total==0) {
			m.put("rows", null);
			m.put("total", total);
			return ResultUtil.ok(m);
		}
		List<HotQaBean> ls =  bbsMapper.getMyFoucsHotQaList((page-1)*10, 10, customerId);
		m.put("rows", ls);
		m.put("total", total);
		return ResultUtil.ok(m);
	}
	
	 /**
	  *  	添加今日热问的评论
	  * @param customerId
	  * @param comment
	  * @return
	  */
	public Object addHotQaComment(Integer customerId,HotQaComment comment) {
		
		//检查评论是否合格
		try {
			checkHotQaComment(comment);
		} catch (ServiceException e) {
			log.info("今日热问评论失败:"+e.getMessage());
			return ResultUtil.fail(e.getMessage());
		}
		//检查是否是官方的用户评论的
		int isOfficial = this.commonService.isUserOfficialAccount(customerId)?1:0;
		HotQaCommentBean cb = new HotQaCommentBean();
		cb.setContent(comment.getContent());
		cb.setCreateTime(new Date());
		cb.setCustomerId(customerId);
		cb.setHotqaId(comment.getHotqaId());
		cb.setIsOfficial(isOfficial);
		cb.setPraiseNum(0);
		int x = this.bbsMapper.addComment(cb);
		if(x<1)
			return ResultUtil.fail("评论失败");
		//评论成功
		return ResultUtil.ok();
	}
	
	private void checkHotQaComment(HotQaComment comment) throws ServiceException{
		
		if(StringUtils.isEmpty(comment.getContent()))
			throw new ServiceException("评论内容必须填写");
		if(comment.getHotqaId()==null||comment.getHotqaId()<1)
			throw new ServiceException("错误");
		//内容检查
		try {
			boolean x = this.commonService.checkContent(comment.getContent());
			if(!x)
				throw new ServiceException("讨论包含敏感词汇");
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("评论包含敏感词汇");
		}
		
	}
	
	public Object praiseHotQaComment(Integer hotqaId,Integer commentId,int customerId,Integer  iHasPraise) {
		if(hotqaId==null)
			return ResultUtil.fail("点赞失败");
		if(commentId==null)
			return ResultUtil.fail("点赞失败");
		if(iHasPraise==null)
			return ResultUtil.fail("点赞失败");
		if(iHasPraise==0){
			//执行点赞
			try {
				int x = this.bbsMapper.addHotQaCommentPraise(commentId, customerId);
				if(x<1)
					return ResultUtil.fail("点赞失败");
				//发送消息提醒
				return ResultUtil.ok();
			} catch (Exception e) {
				if(e instanceof DuplicateKeyException)
					return ResultUtil.fail("你已经点过赞了");
				e.printStackTrace();
				return ResultUtil.fail("点赞失败");
			}
		}
		//取消点赞
		this.bbsMapper.delHotQaCommentPraise(commentId, customerId);
		return ResultUtil.ok();
	}
	
	
	public Object addReplyOnHotQaComment(HotQaCommentReply reply,int customerId) {
		
		if(reply.getCommentId()==null)
			return ResultUtil.fail("回复失败");
		if(reply.getHotqaId()==null)
			return ResultUtil.fail("回复失败");
		if(StringUtils.isEmpty(reply.getReplyContent()))
			return ResultUtil.fail("回复失败");
		//检查回复内容是否合格
		if(!this.commonService.checkContent(reply.getReplyContent()))
			return ResultUtil.fail("回复内容包含敏感词汇");
		//插入数据库
		HotQaCommentReplyBean r = new HotQaCommentReplyBean();
		r.setContent(reply.getReplyContent());
		r.setHotqaId(reply.getHotqaId());
		r.setCreateTime(new Date());
		r.setCustomerId(customerId);
		r.setHotqaCommentId(reply.getCommentId());
		r.setHotqaCommentReplyId(reply.getReplyId()==null?0:reply.getReplyId());
		int isOfficial = this.commonService.isUserOfficialAccount(customerId)?1:0;
		r.setIsOfficial(isOfficial);
		//插入数据库
		int index = this.bbsMapper.addHotQaCommentReply(r);
		if(index <1)
			return ResultUtil.fail("回复失败");
		//消息推送
		return ResultUtil.ok();
	}
	
	/**
	 * <p>我左思右想，评论列表还是搞个缓存。
	 * <p>搞你麻痹的缓存2019-12-16
	 * @param hotQaId
	 * @param customerId
	 * @return
	 */
	public Object getHotQaCommentList(Integer hotQaId,int customerId,Integer page){
		if(hotQaId==null)
			return ResultUtil.fail("获取评论失败");
		long st =System.currentTimeMillis();
		if(page==null||page<1)
			page=1;
		 //查询评论列表，按照官方、时间降序排列
		Map<String,Object> m = new HashMap<>();
		m.put("qaId", hotQaId);
		m.put("page", (page-1)*10);
		m.put("size", 10);
		int total =this.bbsMapper.getHotQaCommentTotal(m);
		if(total==0) {
			m.clear();
			m.put("rows", new ArrayList<>());
			m.put("total", total);
			return ResultUtil.ok(m);
		}
		List<HotQaCommentBean> cs= this.bbsMapper.getHotQaCommentList(m);
		//查询这些评论的回复
		List<HotQaCommentReplyBean> rs = this.bbsMapper.getCommentReplys(cs);
		//查询当前用户得点赞记录
		List<Integer> iPraiseCommentIds = this.bbsMapper.getCurrentUserPraiseRecord(customerId);
		List<HotQaCommentVo> csv = formatCommentAndReply(cs, rs);
		if(iPraiseCommentIds.size()>0) {
			for(HotQaCommentVo c:csv) {
				for(Integer cid:iPraiseCommentIds) {
					if(cid.intValue()==c.getId()) {
						c.setIHasPraise(true);
						break;
					}
				}
			}
		}
		//如果是官方得评论或回复，需要替换用户得名字
		formatOfficialUser(csv);
		m.clear();
		m.put("rows", csv);
		m.put("total", total);
		long ed = System.currentTimeMillis();
		log.info("拉取今日热问评论列表耗时:"+(ed-st)+"ms!");
		return ResultUtil.ok(m);
	}
	
	
	private OfficialAccountbean getOfficial(List<OfficialAccountbean> acs,int customerId) {
		if(acs==null||acs.size()==0)
			return null;
		for(OfficialAccountbean o:acs) {
			if(o.getCustomerId().intValue()==customerId)
				return o;
		}
		
		return null;
	}
	
	private void formatOfficialUser(List<HotQaCommentVo> csv) {
		List<OfficialAccountbean> acs = this.bbsCacheService.getOfficialAccount();
		
		for(HotQaCommentVo c:csv) {
			if(c.getIsOfficial()==1) {
				OfficialAccountbean o = getOfficial(acs, c.getCustomerId());
				if(o!=null) {
					c.setName(o.getOffcialAccountName());
					c.setSellMan(false);
					c.setHeadImg(Constants.OFFCIAL_USER_HEADIMG);
				}else
					c.setIsOfficial(0);
			}
			List<HotQaCommentReplyVo> rvs = c.getReplys();
			if(rvs==null)continue;
			//设置回复内容得官方设置名字
			for(HotQaCommentReplyVo r:rvs) {
				OfficialAccountbean o = getOfficial(acs, r.getCustomerId());
				if(o!=null) {
					r.setReplyerName(o.getOffcialAccountName());
					r.setSellMan(false);
					if(r.getBeReplyedCustomerId()!=null && r.getBeReplyedCustomerId().intValue()
							== o.getCustomerId().intValue())
						r.setBeRelyedName(o.getOffcialAccountName());
				}else
					r.setIsOfficial(0);
			}
		}
	}
	
	
	private List<HotQaCommentVo> formatCommentAndReply(List<HotQaCommentBean> cs,List<HotQaCommentReplyBean> rs) {
		List<HotQaCommentVo> vs = new ArrayList<>();
		//替换为vo
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(HotQaCommentBean c:cs) {
			HotQaCommentVo v = new HotQaCommentVo();
			v.setSellMan(c.getSellManName()!=null);//根据有没有名字判断是不是置业顾问
			v.setName(v.isSellMan()?"置业顾问"+c.getSellManName():c.getUserName());//如果是置业顾问则替换名字
			v.setContent(c.getContent());
			v.setCustomerId(c.getCustomerId());
			v.setDate(sdf.format(c.getCreateTime()));
			v.setHeadImg(c.getHeadImg());
			v.setId(c.getId());
			v.setIsOfficial(c.getIsOfficial());
			v.setPraiseNum(c.getPraiseNum());
			vs.add(v);
		}
		if(vs.size()==0)return vs;
		//格式化回复到评论下
		for(HotQaCommentVo v:vs) {
			int cid = v.getId();
			for(HotQaCommentReplyBean r:rs) {
				if(r.getHotqaCommentId()==cid)
					handleChild(v, r,rs);
			}
		}
		return vs;
		
	}
	
	private void handleChild(HotQaCommentVo v,HotQaCommentReplyBean r,List<HotQaCommentReplyBean> rs ) {
		List<HotQaCommentReplyVo> children = v.getReplys();
		if(children==null)
			v.setReplys(children=new ArrayList<>());
		//转换为vo
		HotQaCommentReplyVo rv = new HotQaCommentReplyVo();
		rv.setSellMan(r.getSellManName()!=null);
		rv.setReplyerName(rv.isSellMan()?"置业顾问"+r.getSellManName():r.getUserName());//如果是置业顾问则使用姓名
		rv.setContent(r.getContent());
		rv.setCustomerId(r.getCustomerId());
		rv.setReplyId(r.getId());
		rv.setIsOfficial(r.getIsOfficial());
		rv.setCommentId(r.getHotqaCommentId());
		//设置这条回复  被回复者得名字
		for(HotQaCommentReplyBean rx:rs) {
			if(rx.getId()==r.getId()) 
				continue;
			if(rx.getHotqaCommentId()!=v.getId())
				continue;
			if(rx.getId()==r.getHotqaCommentReplyId()) {
				//区别置业顾问
				rv.setBeRelyedName(rx.getSellManName()==null
						?rx.getUserName():"置业顾问"+rx.getSellManName());
				rv.setBeReplyedCustomerId(rx.getCustomerId());
				break;
			}
		}
		//加入子集
		children.add(rv);
	}
	
	
	public Object focusHotQa(Integer hotqaId,int customerId,Boolean isHasFoucs) {
		if(hotqaId==null||hotqaId<1)
			return ResultUtil.fail("错误");
		if(isHasFoucs==null)
			isHasFoucs=false;
		if(!isHasFoucs) {
			//添加关注
			try {
				int index = this.bbsMapper.addFocusHotQa(customerId, hotqaId);
				if(index>0)
					return ResultUtil.ok();
				return ResultUtil.fail("关注失败");
			} catch (Exception e) {
				if(e instanceof DuplicateKeyException)
					return  ResultUtil.fail("您已经关注过了");
				e.printStackTrace();
				return ResultUtil.fail("关注失败");
			}
		}
		//取消关注
		this.bbsMapper.delFoucsHotQa(customerId, hotqaId);
		return ResultUtil.ok();
	}
	
	/**生成今日热问的海报*/
	public Object generateHotQaBill(Integer hotQaId, String customerId) {
		if(hotQaId==null||hotQaId<1) {
			return ResultUtil.fail("获取海报失败");
		}
		//从缓存拉取
		HotQaBean qa = getHotQa(hotQaId);
		if(qa==null)
			return ResultUtil.fail("获取海报失败");
		//获取今日热问二维码  先用死的
		byte[] qrCode=null;
		try {
			qrCode = getHotQaQRCode(hotQaId, customerId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取今日热问海报的二维码失败",e);
			return ResultUtil.fail("获取海报失败");
		}
		if(qrCode==null || qrCode.length==0) {
			log.error("获取今日热问海报的二维码失败");
			return ResultUtil.fail("获取海报失败");
		}
//		FileInputStream fis= null;
//		try {
//			fis = new FileInputStream(new File("D:\\text\\qr.png"));
//		} catch (Exception e1) {
//		}
//		byte[] qrCode=null;
//		try {
//			qrCode = new byte[fis.available()];
//			fis.read(qrCode);
//		} catch (Exception e1) {
//		}finally {
//			try {
//				fis.close();
//			} catch (IOException e) {
//			}
//		}
		try {
			String base64 = generateBill(qa, qrCode, hotQaBackGroundUrl);
			return ResultUtil.ok(null, base64);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取今日热问海报的二维码失败");
			return ResultUtil.fail("获取海报失败");
		}
	}

	/**生成海报*/
	private String generateBill(HotQaBean qa,byte[] qrCode,String bgUrl) throws Exception{
		
		//750，1334
		int x = 750;
		int y = 1334;
		//创建底板画布
		BufferedImage billImgBuffer = new BufferedImage(x,y, BufferedImage.TYPE_INT_RGB);// RGB形式
		Graphics2D bill2d = billImgBuffer.createGraphics();
		bill2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//抗锯齿
		bill2d.setBackground(Color.WHITE);//设置背景为白色
		bill2d.clearRect(0, 0, 800, 1500);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形
		//绘制背景图
		drawBackGroundImg(bill2d, x, y);
		//绘制时间
		drawHotQaDate(bill2d, qa.getCreateTime());
		//绘制问题
		int lastY=drawQuestion(bill2d, qa.getQuestion());
		//绘制分割线
		lastY = drawBrLine(bill2d, lastY);
		//绘制回答内容
		lastY = drawAnwser(bill2d, qa.getAnswer(),lastY);
		//绘画小程序二维码
		drawQrCode(qrCode, bill2d);
		//结束绘制,转成byte[]数组并格式化为base64
		bill2d.dispose();
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		ImageIO.write(billImgBuffer, "png",byteOut);
		byte[] b = byteOut.toByteArray();
		return new String(Base64.getEncoder().encode(b));
	}
	
	
	
	private int drawAnwser(Graphics2D bill2d,String anwser,int y) throws IOException {
		if(y>1000) {
			log.info("y轴超过1100，不能再画了");
			return 0;
		}
		HtmlToText h =new HtmlToText();//将富文本转为纯文本
		h.parse(anwser);
		List<String> sections = h.getString();//段落的数据，需要切分
		List<String> lines = splitAnwser(sections);
		if(lines.size()==0)
			return y;
		int x = 94;
		int lastY = y+55;
		bill2d.setPaint(Color.black);
		Font font = new Font("黑体", Font.BOLD, 26);//平方加粗30字号
		bill2d.setFont(font);//设置画笔
		for(int i=0;i<lines.size();i++) {
			int nowY =lastY+(i*40);
			if(nowY>1100) {
				log.info("高度超过1100，不画了");
				break;
			}
			bill2d.drawString(lines.get(i), x,nowY);
		}
		return lastY;
	}
	
	/**将回到的内容、段落切分*/
	private List<String> splitAnwser(List<String> sections){
		List<String> lines = new ArrayList<>();
		float words = 0f;
		StringBuilder sb = new StringBuilder();
		for(String section:sections) {
			char[] cs = section.toCharArray();
			for(int i=0;i<cs.length;i++) {
				sb.append(cs[i]);
				words+= (isEnglish(cs[i])?0.5f:1f);
				float nextLineWrods = i<cs.length-1?nextLineCountAnswer(words,cs[i+1]):words;
				if(i==cs.length-1 || nextLineWrods>21) {
					lines.add(sb.toString());
					words=0f;
					sb = new StringBuilder();
				}
			}
		}
		return lines;
	}
	
	
	/**绘制问题：1、换行问题。2、对其问题。3、中英文问题
	 * @throws IOException 
	 * @throws MalformedURLException */
	private int drawQuestion(Graphics2D bill2d,String question) throws Exception {
		bill2d.setPaint(Color.black);
		Font font = new Font("黑体", Font.BOLD, 30);//平方加粗30字号
		bill2d.setFont(font);//设置画笔
		List<String> lines = splitQeustion2List(question);
		int lineHight = 45;
		int y = 610;
		int x = 186;
		for(int i=0;i<lines.size();i++) {
			int nowY = y+(i*lineHight);
			if(nowY>1100) {
				log.info("绘制问题:y超过1100,不画了");
				break;
			}
			if(i<2) 
				bill2d.drawString(lines.get(i),x,nowY);
			else
				bill2d.drawString(lines.get(i),x-92,nowY);
		}
		if(lines.size()<=2)
			return 680;
		int lastY = y+((lines.size()-1)*lineHight);
		return lastY;
	}
	
	
	private int drawBrLine(Graphics2D bill2d,int y) throws Exception {
		//问题画完后画分割线
		int lastY = y+25;
		BufferedImage brLine = ImageIO.read(new URL(hotQabrLineUrl));
		bill2d.drawImage(brLine,73,lastY, 595, 1, null);
		return lastY;
	}

	private List<String> splitQeustion2List(String question){
		List<String> lines = new ArrayList<>();
		//第一行与第二行行宽486，占16个字，以后行宽580，占19个字，依次切分字符串
		char[] cs = question.toCharArray();
		int index= 0;//行数
		StringBuilder sb = new StringBuilder();
		float lineCount=0f;//每行的字数,中文算2个，英文算1个
		for(int i=0;i<cs.length;i++) {
			sb.append(cs[i]);
			lineCount += (isEnglish(cs[i])?0.45f:1f);
			float nextLineCount = i<cs.length-1?nextLineCount(lineCount,cs[i+1]):lineCount;
			if(index<2 && (nextLineCount>15f || i==cs.length-1)){
				lines.add(sb.toString());
				sb = new StringBuilder();
				index++;
				lineCount=0f;
				continue;
			}
			//第三行起
			if(nextLineCount>18f || i==cs.length-1) {
				lines.add(sb.toString());
				sb = new StringBuilder();
				index++;
				lineCount=0f;
				continue;
			}
		}
		return lines;
	}
	
	
	private float nextLineCount(float lineCount,char c) {
		return 	lineCount += (isEnglish(c)?0.55f:1f);
	}
	 
	
	
	private float nextLineCountAnswer(float lineCount,char c) {
		return 	lineCount += (isEnglish(c)?0.45f:1f);
	}
	
	
	private boolean isEnglish(char c) {
		return (c>=0 && c<=127);
	}
	
	/**绘制热问的日期文字*/
	private void drawHotQaDate(Graphics2D bill2d,Date createTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("MM.dd");
		String date = sdf.format(createTime);
		//rgba(255, 127, 13, 1)
		Color cc = new Color(255, 127, 13);
		bill2d.setPaint(cc);// 设置画笔,设置Paint属性
		Font font = new Font("黑体", Font.PLAIN, 30);//平方加粗30字号
		bill2d.setFont(font);//设置画笔
		bill2d.drawString(date, 575,260);
	}
    
	/**绘制背景图*/
	private void drawBackGroundImg(Graphics2D bill2d,int x,int y) throws Exception {
		// 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容.问题宽度是450px
		BufferedImage bgImg = ImageIO.read(new URL(hotQaBackGroundUrl));
		bill2d.drawImage(bgImg,0,0,x,y,null);
	}
	
	/**绘画二维码*/
    private void drawQrCode(byte[] qrcode,Graphics2D bill2d) throws Exception {
    	//创建二维码的指定大小画布
    	BufferedImage qrCodeImg = new BufferedImage(130, 130,BufferedImage.TYPE_INT_RGB);
		Graphics2D qr2d = qrCodeImg.createGraphics();
		ByteArrayInputStream bin = new ByteArrayInputStream(qrcode);
		//将二维码图片绘制在画布上,按照画布进行缩放
		qr2d.drawImage(ImageIO.read(bin),0,0, 130, 130, null);
		qr2d.dispose();
		//将二维码绘制到背景图上下文
		bill2d.drawImage(qrCodeImg,186,1140,130,130,null);
    }
	
	
	
	private HotQaBean getHotQa(Integer hotQaId) {
		//从缓存拉取
		HotQaBean qa =this.bbsCacheService.getHotQaDetail(hotQaId);
		if(qa==null) {
			//初始化缓存
			qa = this.bbsMapper.getHotQaDetail(hotQaId);
		}
		if(qa==null) {
			return null;
		}
		this.bbsCacheService.setHotQaDetailCache(qa);
		return qa;
	}
	
	private byte[] getHotQaQRCode(int hotQaId, String customerId) {
		String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit"
				+ "?access_token="+this.commonService.getXiaoChengxuToken();
		Map<String,String> m = new HashMap<>();
    	m.put("page", "pages/community/hotASK/main");
    	m.put("scene","hotQaId=" + hotQaId+"&customerId=" + customerId);
    	HttpHeaders headers = new HttpHeaders();
	    //设置请求媒体数据类型
	    headers.setContentType(MediaType.APPLICATION_JSON);
	    String json = JSON.toJSONString(m);
	    HttpEntity<String> formEntity = new HttpEntity<String>(json, headers);
	    ResponseEntity<byte[]> res = restTemplate.postForEntity(url,formEntity, byte[].class);
	    byte[] x = res.getBody();
		return x;
	}
}
